import {Injectable} from '@angular/core';
import {Platform} from '@ionic/angular';
import {Router} from '@angular/router';
import {ToastService} from './toast.service';

@Injectable({
    providedIn: 'root'
})

export class BackService {

    lastBackPress = 0;
    periodExitInterval = 2000;

    constructor(
        private platform: Platform,
        private router: Router,
        private toastSrv: ToastService) {

    }

    registerBackButtonListener(routerArray) {
        document.addEventListener('backbutton', () => {
            const routerUrl = this.router.url;
            const isRootRouter = routerArray.includes(routerUrl);
            if (isRootRouter) {
                const currentBackPress: number = new Date().getTime();
                if (currentBackPress - this.lastBackPress < this.periodExitInterval) {
                    const appKey = 'app';
                    return navigator[appKey].exitApp();
                } else {
                    this.lastBackPress = currentBackPress;
                    this.toastSrv.showToast('再按一次退出');
                }
            }
        }, false);
    }
}
